package com.greenantmall.adapter;

import java.text.DecimalFormat;
import java.util.List;

import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.avos.avoscloud.AVUser;
import com.greenantmall.AntHomeApplication;
import com.greenantmall.R;
import com.greenantmall.activity.ShoppingCartActivity;
import com.greenantmall.bean.Goods;
import com.greenantmall.bean.ShoppingCart;
import com.greenantmall.bean.StoreInfo;
import com.greenantmall.service.RetrieveDataAsyn;
import com.greenantmall.service.RetrieveDataListener;
import com.greenantmall.utils.Const;
import com.greenantmall.utils.UtilTools;
import com.greenantmall.view.DeleteShoppingCartDialog;
import com.greenantmall.view.DeleteShoppingCartDialog.DeleteShoppingCartDialogListener;
import com.nostra13.universalimageloader.core.ImageLoader;

public class ShoppingCartListAdapter extends BaseAdapter
{
    private ShoppingCartActivity mActivity;
    private List<ShoppingCartItemData> mDataList;
    private DecimalFormat mDecimalFormat;

    private ShoppingCartListAdapterListener mShoppingCartListAdapterListener;
    
    private Handler mHandler = new Handler(Looper.getMainLooper());

    public static class ShoppingCartItemData
    {
    	/**
    	 * 0:普通商品行；1：商品休市提示行；2：店铺名称行；3：商品下架提示行；
    	 */
    	public int itemType;
        public ShoppingCart mUIShoppingCart;
        public boolean isChecked;
        /**
         * 所属商铺是否开门
         */
        public boolean isStoreOpen;
        /**
         * 店铺尚未开门还是已经休市
         * 1:尚未开门
         * 2：已经休市
         */
        public int notOpenType;
        /**
         * 店铺名称行的store id
         */
        public String storeId;
        /**
         * 商品是否售罄
         */
        public boolean isSoldOut;
        /**
         * 商品是否下架
         */
        public boolean isOffShelf;
    }

    public interface ShoppingCartListAdapterListener
    {
        public void allItemChecked(boolean isAllChecked);
        public void totalMoneyChanged(boolean weightable, double totalMoney);
    }

    public ShoppingCartListAdapter(ShoppingCartActivity activity,
        List<ShoppingCartItemData> dataList, ShoppingCartListAdapterListener checkCountListener)
    {
        mActivity = activity;
        mDataList = dataList;
        mShoppingCartListAdapterListener = checkCountListener;
        mDecimalFormat = new DecimalFormat("#########.##");
        
        this.totalMoneyChanged();
    }

    public void release()
    {

    }
    
    private void totalMoneyChanged() {
    	double totalMoney = 0;
    	boolean weightable = false;
    	if(mDataList != null) {
    		for(ShoppingCartItemData itemData : mDataList) {
    			if(itemData.itemType != 0 || itemData.isOffShelf) {
    				continue;
    			}
    			
    			if(itemData.isChecked) {
    				try {
    					ShoppingCart usc = itemData.mUIShoppingCart;
        				Goods uiGoods = usc.getGoods();
        				if(uiGoods.isWeighAble()) {
        					weightable = true;
        					break;
        				}
        				else
        				{
        					totalMoney += usc.getCost();
        				}
    				}
    				catch(Exception e) {
    					e.printStackTrace();
    				}
    			}
    		}
    	}
    	
    	if (mShoppingCartListAdapterListener != null)
        {
    		final boolean weightable2 = weightable;
    		final double totalMoney2 = totalMoney;
    		mHandler.post(new Runnable() {
				@Override
				public void run() {
					mShoppingCartListAdapterListener.totalMoneyChanged(weightable2, totalMoney2);
				}
			});
        }
    }

    @Override
    public int getCount()
    {
        int count = 0;
        if (mDataList != null)
        {
            count = mDataList.size();
        }
        return count;
    }

    @Override
    public Object getItem(int position)
    {
        int size = mDataList.size();
        if (position >= 0 && position < size - 1)
        {
            return mDataList.get(position);
        }

        return null;
    }

    @Override
    public long getItemId(int position)
    {
        return 0;
    }

    /**
	 * 0:普通商品行；1：商品休市提示行；2：店铺名称行；3：商品下架提示行；
	 */
    @Override
	public int getItemViewType(int position) {
		return mDataList.get(position).itemType;
	}

	@Override
	public int getViewTypeCount() {
		return 4;
	}

	@Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        Log.d("CEXX", "CEXX ---> getView ---> position : " + position + " ---> type : " + getItemViewType(position));
        View child = convertView;
        int type = this.getItemViewType(position);
        if(type == 0) {
        	ViewHolder holder = null;
            if (child == null)
            {
                child = LayoutInflater.from(mActivity).inflate(R.layout.shopping_cart_listview_item, null);
                holder = new ViewHolder(child);
                child.setTag(holder);
            }
            else
            {
                holder = (ViewHolder) child.getTag();
            }

            holder.setPosition(position);
            ShoppingCartItemData itemData = mDataList.get(position);
            if (itemData != null)
            {
                ShoppingCart usc = itemData.mUIShoppingCart;
                Goods goods = usc.getGoods();
                // CheckBox
                if(itemData.isOffShelf) {
                	holder.getCheckBox().setEnabled(false);
                }
                else {
                	holder.getCheckBox().setEnabled(true);
                	holder.getCheckBox().setChecked(itemData.isChecked);
                }
                // name
                String name = (goods==null ? "" : goods.getDescriptionAndSpecs());
                name = (name==null ? "" : name);
                holder.getTvName().setText(name);
                // price
                double price = (goods==null ? 0 : goods.getRealPrice());
                String unit = (goods==null ? "" : goods.getUnit());
                String yuan = mActivity.getResources().getString(R.string.shopping_cart_price_yuan);
                holder.getTvPrice().setText(mDecimalFormat.format(price) + yuan + " / " + unit);
                // count unit
                double stock = goods.getStock();
                double quantity = usc.getQuantity();
                if(quantity > stock) {
                	usc.put(ShoppingCart.ATTR_QUANTITY, stock);
                	quantity = usc.getQuantity();
                }
                String stepUnit = (goods==null ? "" : goods.getWeighUnit());
                holder.getTvCountUnit().setText(quantity + stepUnit);
                // price by weight
                boolean priceByWeight = (goods==null ? true : goods.isWeighAble());
                if(priceByWeight)
                {
                    holder.getTvPriceByWeight().setVisibility(View.VISIBLE);
                }
                else
                {
                    holder.getTvPriceByWeight().setVisibility(View.GONE);
                }
                // icon
                String iconUrl = (goods==null ? "" : goods.getImageUrl());
                if(!TextUtils.isEmpty(iconUrl)) {
                	ImageLoader.getInstance().displayImage(iconUrl, holder.getViewIcon(),AntHomeApplication.imageDisplayOptions);
                }
                // sold out icon
                if(itemData.isSoldOut && !itemData.isOffShelf) {
                	holder.getViewSoldOutIcon().setVisibility(View.VISIBLE);
                }
                else {
                	holder.getViewSoldOutIcon().setVisibility(View.GONE);
                }
            }
        }
        else if(type == 1) {
        	ViewHolder1 holder1 = null;
            if (child == null)
            {
                child = LayoutInflater.from(mActivity).inflate(R.layout.shopping_cart_listview_item_1, null);
                holder1 = new ViewHolder1(child);
                child.setTag(holder1);
            }
            else
            {
                holder1 = (ViewHolder1) child.getTag();
            }
            
            ShoppingCartItemData itemData = mDataList.get(position);
            if(itemData.notOpenType == 1) {
            	holder1.getTvStoreClosePrompt().setText(mActivity.getResources().getString(R.string.store_close_prompt_1));
            }
            else {
            	holder1.getTvStoreClosePrompt().setText(mActivity.getResources().getString(R.string.store_close_prompt_2));
            }
        }
        else if(type == 2) {
        	ViewHolder2 holder2 = null;
            if (child == null)
            {
                child = LayoutInflater.from(mActivity).inflate(R.layout.shopping_cart_listview_item_2, null);
                holder2 = new ViewHolder2(child);
                child.setTag(holder2);
            }
            else
            {
                holder2 = (ViewHolder2) child.getTag();
            }
            
            holder2.setPosition(position);
            ShoppingCartItemData itemData = mDataList.get(position);
            if(AntHomeApplication.storeInfos != null
            		&& AntHomeApplication.storeInfos.get(itemData.storeId) != null) {
            	StoreInfo storeInfo = AntHomeApplication.storeInfos.get(itemData.storeId);
            	// 店铺名称
            	String storeName = storeInfo.getDescrip();
            	storeName = (storeName==null ? "" : storeName);
            	holder2.getTvStoreName().setText(storeName);
            	// 运费提醒
            	String formatStr = mActivity.getResources().getString(R.string.shopping_cart_freight_prompt);
            	holder2.getTvFreightPrompt().setText(String.format(formatStr, mDecimalFormat.format(storeInfo.getStartcost())));
            	
            	CheckBox checkBox = holder2.getCheckBox();
            	checkBox.setOnCheckedChangeListener(null);
            	checkBox.setChecked(itemData.isChecked);
            	checkBox.setOnCheckedChangeListener(holder2);
            }
            else {
            	holder2.getTvStoreName().setText("");
            	holder2.getTvFreightPrompt().setText("");
            	
            	CheckBox checkBox = holder2.getCheckBox();
            	checkBox.setOnCheckedChangeListener(null);
            	checkBox.setChecked(itemData.isChecked);
            	checkBox.setOnCheckedChangeListener(holder2);
            }
        }
        else if(type == 3) {
        	ViewHolder3 holder3 = null;
            if (child == null)
            {
                child = LayoutInflater.from(mActivity).inflate(R.layout.shopping_cart_listview_item_3, null);
                holder3 = new ViewHolder3(child);
                child.setTag(holder3);
            }
            else
            {
                holder3 = (ViewHolder3) child.getTag();
            }
        }

        return child;
    }
	
	private class ViewHolder1 {
		private View mContentView;
		private TextView mTvStoreClosePrompt;
		
		public ViewHolder1(View contentView) {
			mContentView = contentView;
		}
		
		public TextView getTvStoreClosePrompt() {
			if(mTvStoreClosePrompt == null) {
				mTvStoreClosePrompt = (TextView)mContentView.findViewById(R.id.shopping_cart_item_name);
			}
			return mTvStoreClosePrompt;
		}
	}
	
	private class ViewHolder2 implements OnCheckedChangeListener {
		private View mContentView;
		private CheckBox mCheckBox;
		private TextView mTvStoreName;
		private TextView mTvFreightPrompt;
		
		private int mPosition;
        
		public ViewHolder2(View contentView) {
			mContentView = contentView;
			getCheckBox();
		}
		
		public void setPosition(int position)
        {
            this.mPosition = position;
        }

		public CheckBox getCheckBox() {
			if(mCheckBox == null) {
				mCheckBox = (CheckBox)mContentView.findViewById(R.id.shopping_cart_item_check);
				mCheckBox.setOnCheckedChangeListener(this);
			}
			return mCheckBox;
		}

		public TextView getTvStoreName() {
			if(mTvStoreName == null) {
				mTvStoreName = (TextView)mContentView.findViewById(R.id.shopping_cart_item_store_name);
			}
			return mTvStoreName;
		}

		public TextView getTvFreightPrompt() {
			if(mTvFreightPrompt == null) {
				mTvFreightPrompt = (TextView)mContentView.findViewById(R.id.shopping_cart_item_freight_prompt);
			}
			return mTvFreightPrompt;
		}

		@Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			ShoppingCartItemData currentItemData = mDataList.get(mPosition);
			currentItemData.isChecked = isChecked;
			for(ShoppingCartItemData itemData : mDataList) {
				if(itemData.itemType != 0 || itemData.isOffShelf) {
    				continue;
    			}
				
				if(TextUtils.isEmpty(currentItemData.storeId)) {
					if(TextUtils.isEmpty(itemData.mUIShoppingCart.getStoreId())) {
						itemData.isChecked = isChecked;
					}
				}
				else if(currentItemData.storeId.equals(itemData.mUIShoppingCart.getStoreId())) {
					itemData.isChecked = isChecked;
				}
			}
			notifyDataSetChanged();
		}
	}
	
	private class ViewHolder3 {
		private View mContentView;
		private TextView mTvOffShelfPrompt;
		
		public ViewHolder3(View contentView) {
			mContentView = contentView;
		}
		
		public TextView TvStoreClosePrompt() {
			if(mTvOffShelfPrompt == null) {
				mTvOffShelfPrompt = (TextView)mContentView.findViewById(R.id.shopping_cart_item_name);
			}
			return mTvOffShelfPrompt;
		}
	}

    private class ViewHolder implements OnClickListener, OnCheckedChangeListener
    {
        private View mContentView;

        private TextView mTvStoreName;
        private CheckBox mCheckBox;
        private ImageView mViewIcon;
        private View mViewSoldOutIcon;
        private TextView mTvName;
        private TextView mTvPrice;
        private TextView mTvCountUnit;
        private TextView mTvPriceByWeight;
        private Button mBtnSubtract;
        private Button mBtnAdd;
        
        private int mPosition;
        
        private boolean isAddedOrSubtracted = false;
        
        public ViewHolder(View contentView)
        {
            this.mContentView = contentView;
            getBtnSubtract();
            getBtnAdd();
            getCheckBox();
        }
        
        public void setPosition(int position)
        {
            this.mPosition = position;
        }

		public CheckBox getCheckBox()
        {
            if (mCheckBox == null)
            {
                mCheckBox = (CheckBox) mContentView.findViewById(R.id.shopping_cart_item_check);
                mCheckBox.setOnCheckedChangeListener(this);
            }
            return mCheckBox;
        }

        public ImageView getViewIcon()
        {
            if (mViewIcon == null)
            {
                mViewIcon = (ImageView)mContentView.findViewById(R.id.shopping_cart_item_icon);
            }
            return mViewIcon;
        }
        
        public View getViewSoldOutIcon()
        {
            if (mViewSoldOutIcon == null)
            {
            	mViewSoldOutIcon = mContentView.findViewById(R.id.shopping_cart_item_solo_out_icon);
            }
            return mViewSoldOutIcon;
        }

        public TextView getTvName()
        {
            if (mTvName == null)
            {
                mTvName = (TextView) mContentView.findViewById(R.id.shopping_cart_item_name);
            }
            return mTvName;
        }

        public TextView getTvPrice()
        {
            if (mTvPrice == null)
            {
                mTvPrice =
                    (TextView) mContentView.findViewById(R.id.shopping_cart_item_price);
            }
            return mTvPrice;
        }
        
        public TextView getTvPriceByWeight()
        {
            if (mTvPriceByWeight == null)
            {
                mTvPriceByWeight =
                    (TextView) mContentView.findViewById(R.id.shopping_cart_item_price_by_weight);
            }
            return mTvPriceByWeight;
        }
        
        public TextView getTvCountUnit()
        {
            if (mTvCountUnit == null)
            {
                mTvCountUnit =
                    (TextView) mContentView.findViewById(R.id.shopping_cart_item_count_unit);
            }
            return mTvCountUnit;
        }

        public Button getBtnSubtract()
        {
            if (mBtnSubtract == null)
            {
                mBtnSubtract = (Button) mContentView.findViewById(R.id.shopping_cart_item_subtract);
                mBtnSubtract.setOnClickListener(this);
            }
            return mBtnSubtract;
        }
        
        public Button getBtnAdd()
        {
            if (mBtnAdd == null)
            {
                mBtnAdd = (Button) mContentView.findViewById(R.id.shopping_cart_item_add);
                mBtnAdd.setOnClickListener(this);
            }
            return mBtnSubtract;
        }

        @Override
        public void onClick(View v)
        {
            if (v.equals(mBtnSubtract))
            {
            	Log.d("CEXX", "ShoppingCartListAdapter ---> onClick ---> mBtnSubtract");
            	if(isAddedOrSubtracted){
            		return;
            	}
            	isAddedOrSubtracted = true;
            	
            	try {
            		ShoppingCartItemData itemData = mDataList.get(mPosition);
                    final ShoppingCart uiShoppingCart = itemData.mUIShoppingCart;
                    Goods uiGoods = uiShoppingCart.getGoods();
                    double quantity = uiShoppingCart.getQuantity();
                    double step = uiGoods.getWeighStep();
                    double price = uiGoods.getRealPrice();
                    final String stepUnit = uiGoods.getWeighUnit();
                    Log.d("CEXX", "ShoppingCartListAdapter ---> onClick ---> mBtnSubtract ---> step : " + step);
                    
                    if(quantity - step > 0) {
                    	quantity -= step;
                    	uiShoppingCart.setQuantity(quantity);
                    	uiShoppingCart.setCost(price*quantity);
                    	
                    	RetrieveDataAsyn.getInstance().updateShoppingCart(
                    			uiShoppingCart, 
                    			AVUser.getCurrentUser().getObjectId(), 
                    			-1, 
                    			new RetrieveDataListener()
                            {
                                @Override
                                public void dataRetrieved(int requestId, Object data)
                                {
                                	isAddedOrSubtracted = false;
                                	
                                	if(data != null) {
                                		getTvCountUnit().setText(uiShoppingCart.getQuantity() + stepUnit);
                                    	totalMoneyChanged();
                                    	
                                    	AntHomeApplication.shoppingMap.put(uiShoppingCart.getGoodsid(), uiShoppingCart);
                                        Intent intent = new Intent(Const.SHOPPING_CART_CHANGED);
                                        mActivity.sendBroadcast(intent);
                                	}
                                }
                            });
                    }
                    else {
                    	isAddedOrSubtracted = false;
                    	new DeleteShoppingCartDialog(mActivity,new DeleteShoppingCartDialogListener() {
							@Override
							public void btnSureClicked() {
								isAddedOrSubtracted = true;
								RetrieveDataAsyn.getInstance().removeShoppingCart(
		                    			uiShoppingCart, 
			    						-1, 
			    						new RetrieveDataListener() {
									@Override
									public void dataRetrieved(int requestId, Object data) {
										isAddedOrSubtracted = false;
										if(data != null) {
											mDataList.remove(mPosition);
											mActivity.refreshDataAfterDelete();
											notifyDataSetChanged();
			                                mActivity.sendBroadcast(new Intent(Const.SHOPPING_CART_CHANGED));
										}
									}
								});
							}
						}).show();
                    }
            	}
            	catch(Exception e) {
            		e.printStackTrace();
            	}
            }
            else if(v.equals(mBtnAdd))
            {
            	Log.d("CEXX", "ShoppingCartListAdapter ---> onClick ---> mBtnAdd");
            	
            	if(isAddedOrSubtracted){
            		return;
            	}
            	isAddedOrSubtracted = true;
            	
            	try {
            		ShoppingCartItemData itemData = mDataList.get(mPosition);
                    final ShoppingCart uiShoppingCart = itemData.mUIShoppingCart;
                    final Goods uiGoods = uiShoppingCart.getGoods();
                    double quantity = uiShoppingCart.getQuantity();
                    double step = uiGoods.getWeighStep();
                    double price = uiGoods.getRealPrice();
                    final String stepUnit = uiGoods.getWeighUnit();
                    double stock = uiGoods.getStock();
                    Log.d("CEXX", "ShoppingCartListAdapter ---> onClick ---> mBtnAdd ---> step : " + step);
                    
                    if(quantity + step <= stock) {
                    	quantity += step;
                    	uiShoppingCart.setQuantity(quantity);
                    	uiShoppingCart.setCost(price*quantity);
                    	
                    	RetrieveDataAsyn.getInstance().updateShoppingCart(
                    			uiShoppingCart, 
                    			AVUser.getCurrentUser().getObjectId(), 
                    			-1, 
                    			new RetrieveDataListener()
                            {
                                @Override
                                public void dataRetrieved(int requestId, Object data)
                                {
                                	isAddedOrSubtracted = false;
                                	
                                	if(data != null) {
                                		getTvCountUnit().setText(uiShoppingCart.getQuantity() + stepUnit);
                                    	totalMoneyChanged();
                                    	
                                    	AntHomeApplication.shoppingMap.put(uiShoppingCart.getGoodsid(), uiShoppingCart);
                                        Intent intent = new Intent(Const.SHOPPING_CART_CHANGED);
                                        mActivity.sendBroadcast(intent);
                                	}
                                }
                            });
                    }
                    else {
                    	isAddedOrSubtracted = false;
                    	UtilTools.showMyToast(mActivity, mActivity.getResources().getString(R.string.shopping_cart_out_of_stock));
                    }
            	}
            	catch(Exception e) {
            		e.printStackTrace();
            	}
            }
        }

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {
        	// 是否全部选中
            mDataList.get(mPosition).isChecked = isChecked;
            boolean isAllChecked = true;
            for (ShoppingCartItemData itemData : mDataList)
            {
            	if(itemData.itemType != 0 || itemData.isOffShelf) {
    				continue;
    			}
            	
                if (!itemData.isChecked)
                {
                    isAllChecked = false;
                    break;
                }
            }
            if (mShoppingCartListAdapterListener != null)
            {
            	mShoppingCartListAdapterListener.allItemChecked(isAllChecked);
            }
            
            // 统一店铺的商品是否全部选中
        	boolean isAllCheckedSameStore = true;
        	ShoppingCartItemData currentItemData = mDataList.get(mPosition);
        	String storeId = currentItemData.mUIShoppingCart.getStoreId();
        	if(TextUtils.isEmpty(storeId)) {
        		for (ShoppingCartItemData itemData : mDataList)
                {
                	if(itemData.itemType != 0 || itemData.isOffShelf) {
        				continue;
        			}
                	
                    if(TextUtils.isEmpty(itemData.mUIShoppingCart.getStoreId())) {
                    	if(!itemData.isChecked) {
                    		isAllCheckedSameStore = false;
                    		break;
                    	}
                    }
                }
        		
        		Log.d("CEXX", "CEXX => isAllCheckedSameStore 00 : " + isAllCheckedSameStore);
        		for (ShoppingCartItemData itemData : mDataList)
                {
                	if(itemData.itemType == 2 && TextUtils.isEmpty(itemData.storeId)) {
        				itemData.isChecked = isAllCheckedSameStore;
        				break;
        			}
                }
        	}
        	else {
        		for (ShoppingCartItemData itemData : mDataList)
                {
                	if(itemData.itemType != 0 || itemData.isOffShelf) {
        				continue;
        			}
                	
                    if(storeId.equals(itemData.mUIShoppingCart.getStoreId())) {
                    	if(!itemData.isChecked) {
                    		isAllCheckedSameStore = false;
                    		break;
                    	}
                    }
                }
        		
        		Log.d("CEXX", "CEXX => isAllCheckedSameStore 01 : " + isAllCheckedSameStore);
        		for (ShoppingCartItemData itemData : mDataList)
                {
                	if(itemData.itemType == 2 && storeId.equals(itemData.storeId)) {
        				itemData.isChecked = isAllCheckedSameStore;
        				break;
        			}
                }
        	}
        	notifyDataSetChanged();
            
            totalMoneyChanged();
        }
    }
}
